const {<%=table_name%>, op } = require('../../middleware/baseModel');

 module.exports = { 
    'GET /<%=table_name%>/all' : async (ctx, next) => { 
         const res = await <%=table_name%>.findAll(); 
         return ctx.success(res);
    },

    'GET /<%=table_name%>/detail' : async (ctx, next) => { 
          let id = ctx.get('id') 
         const res = await <%=table_name%>.findOne({where:{id:id}}); 
         return ctx.success(res);
    },


     "POST /<%=table_name%>/export": async (ctx, next) => {
        let rows = [];
        let cols = [];
        let title='<%=table_name%>';

        let tableAttributes = <%=table_name%>.tableAttributes;
        let colKeys = Object.keys(tableAttributes);

        colKeys.forEach((key) => {
        let row = tableAttributes[key];
        let caption = row.comment ? row.comment : row.fieldName;
        cols.push({ caption, type: row.type.__proto__.key === "INTEGER" ? "number" : "string", key: row.field });
        });

        const dbRows = await <%=table_name%>.findAll({});
        rows = dbRows.map((p) => {
            let tempRow = p.toJSON();
            let row = [];
            cols.forEach((col) => {
                row.push(tempRow[col.key]);
            });
            return row;
        });

        return ctx.downFile({title, rows, cols });
  },

    'POST /<%=table_name%>/page' : async (ctx, next) => { 
         let param = ctx.getPageSize()
         let row = ctx.getBody();
         let {key,value}=row.seachOption
         let where={} 
         if(key&&value){
             where[key]={ [op.like]:'%' +value + '%'}
         }
         
         const res = await <%=table_name%>.findAndCountAll({
               where,
               order: [["id", "DESC"]],
               ...param,
         }); 
         return ctx.success(res);
    },
   
    'POST /<%=table_name%>/add': async (ctx, next) => {
        let row = ctx.getBody(); 
        const res = await <%=table_name%>.create(row); 
        return ctx.success(res);
    },
    'POST /<%=table_name%>/edit': async (ctx, next) => {
        let row = ctx.getBody(); 
        let id = ctx.get('id') 
        const res = await <%=table_name%>.update(row, { where: { id: id }, individualHooks: true  });
        return ctx.success(res); 
    }, 
                         
    'POST /<%=table_name%>/del': async (ctx, next) => {
        let id = ctx.get('id') 
        const res = await <%=table_name%>.destroy({ where: { id: id }, individualHooks: true });
        return ctx.success(res); 
     } 
 };